//
//  HomeChatViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/9/7.
//

import Foundation
class HomeChatViewModel: BaseViewModel {
    @Published var tableItem : [ChatTableItem] = []
    @Published var selectId: String = "1" // 必须有初始值（非空）
    private var initSelectId = false
    private var delay : TimeInterval = 0

    override init() {
        super.init()
        self.pageSize = 1000
        self.addObserve(self, .refreshHomeChat) { (selfInstance, update: Bool) in
            //刷新列表
            selfInstance.getTab()
        }
        self.addObserve(self, .updateAiRole) { (selfInstance, update: Bool) in
            self.delay = 500
            selfInstance.getTab()
        }
    }
    
    func getTab() {
        var isRole = false
        request(isLoading: false) {
            if self.delay > 0 {
                //保存成功，需要延迟下，马上刷新有bug,不会有结果
                try await Task.delay(self.delay)
            }
            var tableItem: [ChatTableItem] = []
            if let roleId = try await BackupsManager.shared.getDelegateConfig()?.getOften() {
                let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: roleId)
                var item = ChatTableItem(uuid: aiRole?.objectId ?? UUID().uuidString, id: "0", name: aiRole?.name ?? "")
                item.aiRole = aiRole
                tableItem.append(item)
                isRole = true
            }
            tableItem.append(ChatTableItem(uuid: UUID().uuidString, id: "1", name: "聊天"))
            tableItem.append(ChatTableItem(uuid: UUID().uuidString, id: "2", name: "心灵"))
            tableItem.append(ChatTableItem(uuid: UUID().uuidString, id: "3", name: "总览"))
            return tableItem
        } suc: { list in
            self.delay = 0
            self.tableItem = list
            //没有初始化过，则初始化为0
            if !self.initSelectId && isRole {
                self.selectId = "0"
            }
            self.initSelectId = true
        } fail: {
            showLog($0.message)
        }
    }
}
